<?php

namespace core\traits;

use Throwable;

trait WidgetView
{
    public function view(array $vars = [])
    {
        $widget_explode = explode('\\', get_called_class());
        $traceobj = debug_backtrace();
        $viewpath = base_path() . '/component/widget/'
            . $widget_explode[2] . '/' . $widget_explode[3] . '/template/Index/' . $traceobj[1]['function'] . '.php';
        return $this->render($viewpath, $vars);
    }

    /**
     * 重写渲染方法
     *
     * @param string $path
     * @param array $vars
     * @return void
     */
    private function  render(string $path, array $vars)
    {
        extract(array_merge(request()->_view_vars, $vars));
        ob_start();
        try {
            include $path;

            foreach ($vars as $key => $var) {
                unset($vars[$key]);
            }
        } catch (Throwable $e) {
            ob_end_clean();
            throw $e;
        }
        return ob_get_clean();
    }
}
